package cn.tedu.submarine;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Arrays;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

public class World extends JPanel {
    public static final int WIDTH = 641;
    public static final int HEIGHT = 479;

    public static final int GAME_OVER = 0;
    public static final int RUNNING = 1;
    public static final int PAUSE = 2;
    private int state = RUNNING;

    private BattleShip ship = new BattleShip();
    private SeaObject[] submarines ={};
    private Mine[] mines = {};
    private Bomb[] bombs = {};

    /**
     * 产生潜艇对象
     * @return 三种潜艇其一
     */
    private SeaObject nextSubmarine(){
        Random rand = new Random();
        int type = rand.nextInt(20);
        if (type<5){
            return new ObserveSubmarine();
        }else if(type<10){
            return new TorpedoSubmarine();
        }else{
            return new MineSubmarine();
        }
    }

    /**
     * 潜艇入场
     */
    private int subEnterIndex = 0;
    private void submarineEnterAction(){
        subEnterIndex++;
        if(subEnterIndex%40==0){
            SeaObject obj = nextSubmarine();
            submarines = Arrays.copyOf(submarines,submarines.length+1);
            submarines[submarines.length-1] = obj;
        }
    }

    /**
     * 水雷潜艇发射水雷，水雷入场
     */
    private int minesEnterIndex = 0;
    private void minesEnterAction(){
        minesEnterIndex++;
        if(minesEnterIndex%100==0){
           for (int i =0; i<submarines.length-1;i++){
               if(submarines[i] instanceof MineSubmarine){
                   MineSubmarine ms  = (MineSubmarine) submarines[i];
                   Mine obj = ms.shootMine();
                   mines = Arrays.copyOf(mines,mines.length+1);
                   mines[mines.length-1] =obj;
               }
           }
        }
    }

    /**
     * 海洋对象移动
     */
    private void moveAction(){
        for (int i = 0;i<submarines.length;i++){
            submarines[i].move();
        }
        for (int i =0;i<mines.length;i++){
            mines[i].move();
        }
        for(int i=0;i<bombs.length;i++){
            bombs[i].move();
        }
    }

    /**
     * 删除越界潜艇，炸弹，水雷对象
     */
    private void outOfBoundsAction(){
        for (int i =0;i<submarines.length;i++){
            if (submarines[i].outOfBounds() ||submarines[i].isDead()){
                submarines[i]=submarines[submarines.length-1];
                submarines = Arrays.copyOf(submarines,submarines.length-1);
            }
        }
        for (int i =0;i<mines.length;i++){
            if (mines[i].outOfBounds() || mines[i].isDead()){
                mines [i]=mines[mines.length-1];
                mines =Arrays.copyOf(mines,mines.length-1);
            }
        }
        for (int i = 0;i<bombs.length-1;i++){
            if(bombs[i].outOfBounds() || bombs[i].isDead()){
                bombs[i]=bombs[bombs.length-1];
                bombs = Arrays.copyOf(bombs,bombs.length-1);
            }
        }
    }

    /**
     * 炸弹与潜艇的碰撞
     */
    private int score =0;
    private void bombBangAction(){
        for (int i = 0;i<submarines.length;i++){
            SeaObject obj = submarines[i];
            for (int j = 0;j< bombs.length;j++){
                Bomb b = bombs[j];
                if (obj.isLive() && b.isLive() && obj.isHit(b)){
                    obj.goDead();
                    b.goDead();
                    if (obj instanceof EnemyScore){
                        EnemyScore es = (EnemyScore) obj;
                        score +=es.getScore();
                    }
                    if(obj instanceof EnemyLife){
                        EnemyLife el = (EnemyLife) obj;
                        int num = el.getLife();
                        ship.addLife(num);
                    }
                }
            }
        }
    }

    /**
     * 水雷与战舰的碰撞
     */
    private void mineBangAction(){
        for(int i =0;i<mines.length;i++){
            Mine m = mines[i];
            if(ship.isLive() && m.isLive() && ship.isHit(m)){
                m.goDead();
                ship.subtractLife();
            }
        }
    }

    /**
     * 检测游戏结束
     */
    private void checkGameOverAction(){
        if (ship.getLife()<=0)
            state = GAME_OVER;
    }

    private void action(){
        KeyAdapter k =new KeyAdapter() {
            @Override
            public void keyReleased(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_P){
                    if (state==RUNNING){
                        state = PAUSE;
                    }else if(state ==PAUSE){
                        state = RUNNING;
                    }
                }

                if (state ==RUNNING){
                    if (e.getKeyCode() ==KeyEvent.VK_SPACE){
                        Bomb obj =ship.shootBombs();
                        bombs = Arrays.copyOf(bombs,bombs.length+1);
                        bombs[bombs.length-1]=obj;
                    }
                    if (e.getKeyCode() == KeyEvent.VK_RIGHT){
                        ship.moveRight();
                    }
                    if(e.getKeyCode() == KeyEvent.VK_LEFT){
                        ship.moveLeft();
                    }
                }
            }
        };
        this.addKeyListener(k);


            Timer timer = new Timer();
            int interval = 10;
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    if (state ==RUNNING){
                        submarineEnterAction();
                        minesEnterAction();
                        moveAction();
                        outOfBoundsAction();
                        bombBangAction();
                        mineBangAction();
                        checkGameOverAction();

                        repaint();
                    }
                }
            },interval,interval);

    }

    public void paint(Graphics g){
        Images.sea.paintIcon(null,g,0,0);
        ship.paintImage(g);
        for (int i = 0;i<submarines.length;i++){
            submarines[i].paintImage(g);
        }
        for (int i =0;i<mines.length;i++){
            mines[i].paintImage(g);
        }
        for(int i =0;i<bombs.length;i++){
            bombs[i].paintImage(g);
        }

        g.drawString("SCORE:"+score,200,50);
        g.drawString("LIFE:"+ ship.getLife(),400,50);

        if(state == GAME_OVER){
            Images.gameover.paintIcon(null,g,0,0);
        }
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame(); //3.
        World world = new World(); //会创建窗口中的那一堆对象
        world.setFocusable(true);
        frame.add(world);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(WIDTH+5, HEIGHT+21);
        frame.setLocationRelativeTo(null);
        frame.setResizable(false);
        frame.setVisible(true); //自动调用paint()方法

        world.action();
    }


}
